<template>
    <div class="comment-container">
        <h3>发表评论</h3>
        <hr>
        <textarea placeholder="输入BB内容。。。（只能吐槽120jiujiujiu）" maxlength="120" v-model="content"></textarea>
        <mt-button type="primary" size="large" @click="publishComment()">发表评论</mt-button>       
        <div class="cmt-list">
            <div class="cmt-item" v-for="(item,i) in comments" :key="i">
                <div class="cmt-title">
                    第{{i+1}}楼&nbsp;&nbsp;用户：{{item.user_name}}&nbsp;&nbsp;发表时间：{{item.add_time|dateFormat}}
                </div>
                <div class="cmt-body">
                    {{item.content === 'undefined'?'这只猪头没写东西':item.content}}
                </div>
            </div>
        </div>
        <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
    </div>
</template>
<script>
import {Toast} from 'mint-ui' 
//由于axios的post请求存在跨域问题，要使用qs插件  
import qs from 'qs'
export default {
    data(){
        return {
            pageindex:1,
            comments:[],
            content:""
        }
    },
    props:['id'],
    created(){
       this.getComments()
    },
    methods:{
        async getComments(){
            const {data} = await this.$http.get('api/getcomments/'+this.id+'?pageindex='+this.pageindex)
                if(data.status === 0){
                    this.comments = this.comments.concat(data.message)
                }
                else{
                    Toast('获取评论失败biubiubiu...')
                }
        },
        async publishComment(){
            if(this.content.trim().length == 0){
                Toast('死肥猪，啥都不写，就想提交？？？')
            }else{
                const {data} = await this.$http.post('api/postcomment/'+this.id,qs.stringify({
                    content:this.content.trim()
                }))
                if(data.status === 0){
                    var cmt = {
                        content:this.content.trim(),
                        add_time:Date.now(),
                        user_name:'匿名用户'
                    }
                    this.comments.unshift(cmt)
                    this.content = ''
                }else{
                    Toast('hen 遗憾  发布失败，，，')
                }
            }
        },
        getMore(){
            this.pageindex++
            this.getComments()
        }
    }
}
</script>
<style lang="scss" scoped>
.comment-container{
    h3{
        font-size: 18px;
    }
    textarea{
        font-size: 14px;
        margin: 0;
        height: 85px;
    }
    .cmt-list{
        margin: 4px 0;
        .cmt-item{
            font-size: 13px;
            .cmt-title{
                background-color: #ccc;
                line-height: 30px;
            }
            .cmt-body{
                text-indent: 2rem;
                line-height: 35px;
            }
        }

    }
}
</style>
